package com.china.produce.service;

import com.china.produce.listener.ContextReadListener;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.servlet.AsyncContext;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2024/7/6
 */
@Service
public class ContextService {

    private static final Logger LOG = LoggerFactory.getLogger(ContextService.class);

    @Autowired
    @Qualifier("restSimpleEsClient")
    public RestClient restClient;

    /**
     * 异步上下文处理
     *
     * @param request
     */
    public void asyncDispatch(HttpServletRequest request) {
        try {
            AsyncContext asyncContext = request.startAsync();
            ServletInputStream inputStream = request.getInputStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            //添加监听器
            inputStream.setReadListener(new ContextReadListener(inputStream, asyncContext, outputStream, restClient));

        }catch (Exception exception) {
            LOG.error("处理日志失败 {}", exception.getMessage());
        }
    }
}
